// 模拟数据
const mockIssues = [
    {
        id: 1,
        title: '用户登录模块性能优化',
        status: '处理中',
        priority: '紧急',
        creator: 'zhang.san',
        createTime: '2024-01-05 09:30:00',
        updateTime: '2024-01-08 14:20:15'
    },
    {
        id: 2,
        title: '数据库连接池内存泄漏问题',
        status: '待处理',
        priority: '紧急',
        creator: 'li.si',
        createTime: '2024-01-06 11:25:30',
        updateTime: '2024-01-06 11:25:30'
    },
    {
        id: 3,
        title: '订单系统并发处理优化',
        status: '已解决',
        priority: '紧急',
        creator: 'wang.wu',
        createTime: '2024-01-02 15:40:22',
        updateTime: '2024-01-07 16:45:10'
    },
    {
        id: 4,
        title: '支付接口异常处理完善',
        status: '处理中',
        priority: '普通',
        creator: 'zhao.liu',
        createTime: '2024-01-04 10:15:45',
        updateTime: '2024-01-08 09:30:20'
    },
    {
        id: 5,
        title: '用户反馈模块样式调整',
        status: '已关闭',
        priority: '低优先级',
        creator: 'chen.qi',
        createTime: '2024-01-03 14:20:00',
        updateTime: '2024-01-05 11:10:30'
    }
];

// 当前页码和每页显示数量
let currentPage = 1;
let pageSize = 10;

// DOM 加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    initializeDateSelects();
    renderTable(mockIssues);
    
    // 绑定搜索按钮事件
    document.querySelector('.search-btn').addEventListener('click', handleSearch);
    
    // 绑定重置按钮事件
    document.querySelector('.reset-btn').addEventListener('click', handleReset);
    
    // 绑定新建问题按钮事件
    document.querySelector('.add-issue-btn').addEventListener('click', handleAddIssue);
    
    // 绑定分页按钮事件
    document.querySelectorAll('.page-buttons button').forEach(button => {
        button.addEventListener('click', (e) => handlePageChange(e.target));
    });
    
    // 绑定每页显示数量变化事件
    document.querySelector('.page-size').addEventListener('change', handlePageSizeChange);
});

// 初始化日期选择器
function initializeDateSelects() {
    const currentYear = new Date().getFullYear();
    const yearSelects = document.querySelectorAll('.year-select');
    const monthSelects = document.querySelectorAll('.month-select');
    const daySelects = document.querySelectorAll('.day-select');
    
    // 填充年份选项
    yearSelects.forEach(select => {
        for(let year = currentYear - 5; year <= currentYear + 5; year++) {
            const option = document.createElement('option');
            option.value = year;
            option.textContent = year;
            select.appendChild(option);
        }
    });
    
    // 填充月份选项
    monthSelects.forEach(select => {
        for(let month = 1; month <= 12; month++) {
            const option = document.createElement('option');
            option.value = month.toString().padStart(2, '0');
            option.textContent = month;
            select.appendChild(option);
        }
    });
    
    // 填充日期选项
    daySelects.forEach(select => {
        for(let day = 1; day <= 31; day++) {
            const option = document.createElement('option');
            option.value = day.toString().padStart(2, '0');
            option.textContent = day;
            select.appendChild(option);
        }
    });
}

// 渲染表格
function renderTable(data) {
    const tbody = document.getElementById('issuesTableBody');
    tbody.innerHTML = '';
    
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pageData = data.slice(startIndex, endIndex);
    
    pageData.forEach(issue => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${issue.title}</td>
            <td><span class="status-badge status-${getStatusClass(issue.status)}">${issue.status}</span></td>
            <td><span class="priority-${getPriorityClass(issue.priority)}">${issue.priority}</span></td>
            <td>${issue.creator}</td>
            <td>${issue.createTime}</td>
            <td>${issue.updateTime}</td>
            <td>
                <button class="action-btn edit-btn" onclick="handleEdit(${issue.id})">修改</button>
                <button class="action-btn delete-btn" onclick="handleDelete(${issue.id})">删除</button>
            </td>
        `;
        tbody.appendChild(tr);
    });
    
    updatePagination(data.length);
}

// 获取状态对应的样式类
function getStatusClass(status) {
    switch(status) {
        case '处理中': return 'processing';
        case '待处理': return 'pending';
        case '已解决': return 'completed';
        case '已关闭': return 'closed';
        default: return '';
    }
}

// 获取优先级对应的样式类
function getPriorityClass(priority) {
    switch(priority) {
        case '紧急': return 'urgent';
        case '普通': return 'normal';
        case '低优先级': return 'low';
        default: return '';
    }
}

// 处理搜索
function handleSearch() {
    const statusFilter = document.getElementById('statusFilter').value;
    const priorityFilter = document.getElementById('priorityFilter').value;
    const searchKeyword = document.getElementById('searchKeyword').value.toLowerCase();
    
    // 获取日期值
    const startYear = document.getElementById('yearSelect').value;
    const startMonth = document.getElementById('monthSelect').value;
    const startDay = document.getElementById('daySelect').value;
    const endYear = document.getElementById('endYearSelect').value;
    const endMonth = document.getElementById('endMonthSelect').value;
    const endDay = document.getElementById('endDaySelect').value;
    
    let filteredData = mockIssues.filter(issue => {
        let matchStatus = !statusFilter || issue.status === statusFilter;
        let matchPriority = !priorityFilter || issue.priority === priorityFilter;
        let matchKeyword = !searchKeyword || 
            issue.title.toLowerCase().includes(searchKeyword) || 
            issue.creator.toLowerCase().includes(searchKeyword);
        let matchDate = true;
        
        if (startYear && startMonth && startDay && endYear && endMonth && endDay) {
            const startDate = new Date(`${startYear}-${startMonth}-${startDay}`);
            const endDate = new Date(`${endYear}-${endMonth}-${endDay}`);
            const issueDate = new Date(issue.createTime);
            matchDate = issueDate >= startDate && issueDate <= endDate;
        }
        
        return matchStatus && matchPriority && matchKeyword && matchDate;
    });
    
    currentPage = 1;
    renderTable(filteredData);
}

// 处理重置
function handleReset() {
    // 重置所有筛选条件
    document.getElementById('statusFilter').value = '';
    document.getElementById('priorityFilter').value = '';
    document.getElementById('searchKeyword').value = '';
    document.querySelectorAll('.year-select, .month-select, .day-select').forEach(select => {
        select.value = '';
    });
    
    // 重新渲染表格
    currentPage = 1;
    renderTable(mockIssues);
}

// 更新分页信息
function updatePagination(totalItems) {
    const totalPages = Math.ceil(totalItems / pageSize);
    const paginationDiv = document.querySelector('.page-buttons');
    paginationDiv.innerHTML = '';
    
    // 添加上一页按钮
    const prevButton = document.createElement('button');
    prevButton.textContent = '上一页';
    prevButton.classList.add('prev-btn');
    prevButton.disabled = currentPage === 1;
    prevButton.addEventListener('click', () => handlePageChange('prev'));
    paginationDiv.appendChild(prevButton);
    
    // 计算要显示的页码范围
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, startPage + 4);
    
    // 调整startPage以确保始终显示5个页码（如果有足够的页数）
    if (endPage - startPage < 4 && totalPages > 5) {
        startPage = Math.max(1, endPage - 4);
    }
    
    // 添加页码按钮
    for (let i = startPage; i <= endPage; i++) {
        const button = document.createElement('button');
        button.textContent = i;
        button.classList.add('page-num');
        if (i === currentPage) {
            button.classList.add('active');
        }
        button.addEventListener('click', () => handlePageChange(i));
        paginationDiv.appendChild(button);
    }
    
    // 添加下一页按钮
    const nextButton = document.createElement('button');
    nextButton.textContent = '下一页';
    nextButton.classList.add('next-btn');
    nextButton.disabled = currentPage === totalPages;
    nextButton.addEventListener('click', () => handlePageChange('next'));
    paginationDiv.appendChild(nextButton);
    
    // 更新总条数显示
    document.querySelector('.pagination span').textContent = `共 ${totalItems} 条`;
}

// 处理新建问题
function handleAddIssue() {
    // TODO: 实现新建问题的弹窗或页面跳转
    alert('新建问题功能待实现');
}

// 处理编辑
function handleEdit(id) {
    // TODO: 实现编辑功能
    alert(`编辑问题 ID: ${id}`);
}

// 处理删除
function handleDelete(id) {
    if (confirm('确定要删除这个问题吗？')) {
        // TODO: 实现删除功能
        alert(`删除问题 ID: ${id}`);
    }
}

// 处理分页
function handlePageChange(action) {
    const totalPages = Math.ceil(mockIssues.length / pageSize);
    
    if (action === 'prev' && currentPage > 1) {
        currentPage--;
    } else if (action === 'next' && currentPage < totalPages) {
        currentPage++;
    } else if (typeof action === 'number') {
        currentPage = action;
    }
    
    renderTable(mockIssues);
}

// 处理每页显示数量变化
function handlePageSizeChange(e) {
    pageSize = parseInt(e.target.value);
    currentPage = 1;
    renderTable(mockIssues);
} 